// cn/practice/service/impl/StudentServiceImpl.java

package cn.practice.service.impl;

import cn.practice.entity.Student;
import cn.practice.listener.StudentReadListener;
import cn.practice.mapper.StudentMapper;
import cn.practice.service.StudentService;
import cn.practice.service.result.ImportResult;
import cn.practice.service.result.Result;
import com.alibaba.excel.EasyExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<ImportResult> importStudents(MultipartFile file) {
        int[] total = {0};
        List<Student> buffer = new ArrayList<>();
        int DB_BATCH_SIZE = 5;
        StudentReadListener listener = new StudentReadListener(DB_BATCH_SIZE, students -> {
            buffer.addAll(students);
            total[0] += students.size();

            if (buffer.size() >= DB_BATCH_SIZE) {
                // ✅ 直接在事务中插入，不走单独方法
                try {
                    studentMapper.saveBatch(new ArrayList<>(buffer));
                    buffer.clear();
                } catch (Exception e) {
                    throw new RuntimeException("插入失败，触发回滚", e);
                }
            }
        }, total);

        try (InputStream inputStream = file.getInputStream()) {
            EasyExcel.read(inputStream, Student.class, listener)
                    .sheet()
                    .doRead();
        } catch (Exception e) {
            return Result.failed("文件解析失败: " + e.getMessage());
        }

        // 处理最后一批
        if (!buffer.isEmpty()) {
            studentMapper.saveBatch(buffer);
        }

        ImportResult result = new ImportResult(listener.getErrorList(), total[0]);
        return Result.success(result);
    }
}